package session

import (
	"crypto/md5"
	"fmt"
	"gitee.com/jjj-server/mdb"
	"log"
	"strconv"
	"time"
)

// 权限控制变量
const(
	P_PASSWD = 0x01				// 修改密码
	P_EDITPROFILE_SELF = 0x02	// 修改个人档案
	P_LOGIN = 0x03				// 登录
	P_UNLOGIN = 0x04			// 注销
	P_READCONTENT = 0x05		// 阅读内容
	P_POSTCOMMENT = 0x06		// 发布评论
	P_DELCOMMENT = 0x07			// 删除评论

	P_ADDUSER = 0x0f			// 添加用户
	P_DELUSER = 0x1f			// 删除用户
	P_USER = 0x2f				// 所有用户权限
	P_OP = 0xff					// 管理员权限
)

// 建立session
func AddSession(username string) bool{
	db := mdb.ConnectDB()
	defer db.Close()
	token := generateSession(username)
	_,err := db.Exec("INSERT INTO session(username, session_key, expires) VALUES (?,?,?)",username,token,30)
	if err != nil {
		log.Println("<- Failed to create session: ",err)
		return false
	}
	return true
}

// 创建session_code
func generateSession(username string)string{
	log.Println("-> Start generating session_code(token).")
	var token string
	unixn := strconv.Itoa(int(time.Now().Unix())-1966)	// 现在的时间戳
	has := md5.Sum([]byte(unixn+username))
	token = fmt.Sprintf("%x",has)
	log.Println("<- Generated session_code(token): ",token)
	return token
}

// 获取session_code
func GetSessionCode(username string)string{
	db := mdb.ConnectDB()
	defer db.Close()
	var token string
	row := db.QueryRow("SELECT session_key FROM session WHERE username = ? ",username)
	err := row.Scan(&token)
	if err != nil{
		log.Println(err)
		return "false"
	}
	return token
}
// 删除session
func DelSession(token string)bool{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("DELETE FROM session WHERE token = ?",token)
	if err != nil{
		log.Println("<- Failed to delete session: ",err)
		return false
	}
	return true
}

// 检验Session权限
func CheckSession(token string)bool{
	db := mdb.ConnectDB()
	defer db.Close()
	row := db.QueryRow("SELECT username FROM session WHERE session_key = ?",token)
	var username string
	row.Scan(&username)
	if username != ""{
		return true
	}
	return false
}
// 登录
func Login(username string,password string) bool{
	db := mdb.ConnectDB()
	defer db.Close()
	row := db.QueryRow("SELECT password FROM users WHERE username = ? ",username)
	var t_password string
	err := row.Scan(&t_password)
	if err != nil{
		log.Println("<- Failed to get user password: ",err)
		return false
	}
	if password == t_password {
		log.Println("-> USER LOGIN: ",username)
		log.Println("<- Right Password")
		AddSession(username)
		return true
	}
	log.Println("<- Wrong Password")
	return false
}

// 注销
func Unlogin(token string) bool{
	if CheckSession(token){
		success := DelSession(token)
		if !success{
			log.Println("<- Failed to delete session")
			return false
		}
		return true
	}
	log.Println("<- Wrong Token")
	return false
}